package com.azt.back.action.admin;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.azt.utils.SessionUtils;

//该注解用来指定一个URI，客户端可以通过这个URI来连接到WebSocket。类似Servlet的注解mapping。无需在web.xml中配置。
@ServerEndpoint("/ws/{relationId}/{userCode}/websocket.do")
public class WebsocketEndPoint {
	// 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
	private static int onlineCount = 0;

	private static Log log = LogFactory.getLog(WebsocketEndPoint.class);



	@OnOpen
	public void onOpen(@PathParam("relationId") String relationId, @PathParam("userCode") int userCode, Session session) {
		
/*		try {
			//延时建立连接2秒,方便中断操作
			Thread.sleep(2000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		*/
		
		Session oSession = SessionUtils.get(relationId, userCode);
		if(oSession != null){
			try {
				oSession.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			SessionUtils.remove(relationId, userCode);
		}
		
		addOnlineCount(); // 在线数加1
		System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
		log.info("Websocket Start Connecting:" + SessionUtils.getKey(relationId, userCode));
		SessionUtils.put(relationId, userCode, session);
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(@PathParam("relationId") String relationId, @PathParam("userCode")  int userCode, Session session) {
		subOnlineCount(); // 在线数减1
		System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
		SessionUtils.remove(relationId, userCode);
	}

	/**
	 * 收到客户端消息后调用的方法
	 * 
	 * @param message
	 *            客户端发送过来的消息
	 * @param session
	 *            可选的参数
	 */
	@OnMessage
	public void onMessage(@PathParam("relationId") String relationId, @PathParam("userCode") int userCode, String message, Session session) {
		System.out.println("来自客户端的消息:" + message);
	}

	/**
	 * 发生错误时调用
	 * 
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("链接关闭");
		//error.printStackTrace();
	}

	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		WebsocketEndPoint.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		WebsocketEndPoint.onlineCount--;
	}
}
